package ru.stepuk.modeller.distributions;

import java.util.Map;
import ru.stepuk.modeller.generators.RandomNumberGenerator;

/**
 *
 * @author ivan
 */
class NormalDistribution implements Distribution {

    private boolean hasPair = false;
    private double another;
    private RandomNumberGenerator g;
    private double mean;
    private double variance;
    private double deviation;

    public NormalDistribution(double mean, double variance, RandomNumberGenerator g) {
        if (variance < 0) {
            throw new IllegalArgumentException();
        }
        this.g = g;
        this.mean = mean;
        this.variance = variance;
        this.deviation = Math.sqrt(variance);
    }

    public double nextValue() {
        // Преобразование Бокса — Мюллера
        if (hasPair) {
            hasPair = false;
            return another;
        }
        
        double x, y, s;
        do {
            x = 2 * g.nextValue() - 1;
            y = 2 * g.nextValue() - 1;
            s = x * x + y * y;
        } while (s >= 1 || s == 0);

        double multiplier = Math.sqrt(-2 * Math.log(s) / s);
        another = mean + deviation * (x * multiplier);
        hasPair = true;

        return mean + deviation * (y * multiplier);
    }

    public Map<String, Object> getParameters() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

}
